#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/interrupt.h>


struct c0_dev{
	unsigned int dev_major;
	struct class *devcls;
	struct device *dev;
	int kvalue;
	int value;
	int irqnum;
};
struct c0_dev *c0;


int c0_open(struct inode *inode,struct file *filp)
{
	printk("---------%s--------\n",__FUNCTION__);
	return 0;
}
ssize_t c0_read(struct file *filp,char __user *buf,size_t count,loff_t *fpos)
{
	c0->kvalue = 520;
	if(copy_to_user(buf,&c0->kvalue,count)!=0)
	{
		printk("copy_to_user failed\n");
		return -EFAULT;
	}
	return 0;
}
ssize_t c0_write(struct file *filp,const char __user *buf,size_t count,loff_t *fpos)
{
	if(copy_from_user(&c0->value,buf,count)!= 0)
	{
		printk("copy_from_user failed\n");
		return -EFAULT;
	}
	printk("kernel value: %d\n",c0->value);
	return 0;
}
int c0_close(struct inode *inode,struct file *filp)
{
	printk("---------%s--------\n",__FUNCTION__);
	return 0;
}

const struct file_operations my_fops={
	.open = c0_open,
	.read = c0_read,
	.write = c0_write,
	.release = c0_close,
};

irqreturn_t irq_handler(int irqn,void *devid)
{
	printk("---------irq-------\n");
	return IRQ_HANDLED;

}

static int __init chr_dev_init(void)
{
	int ret;
	c0=(struct c0_dev*)kmalloc(sizeof(struct c0_dev),GFP_KERNEL);
	if(IS_ERR(c0))
	{
		printk("kmalloc falied\n");
		return -1;
	}
	c0->irqnum=0;
	c0->dev_major=register_chrdev(0,"chr_dev_test",&my_fops);
	c0->devcls = class_create(THIS_MODULE,"chr_cls");
	c0->dev = device_create(c0->devcls,NULL,MKDEV(c0->dev_major,0),NULL,"c0");
	ret = request_irq(c0->irqnum,irq_handler,IRQF_TRIGGER_NONE,"irq",NULL);
	if(ret != 0)
	{
		printk("request_irq failed\n");
		return -1;
	}
	return 0;

}

static void __exit chr_dev_exit(void)
{
	free_irq(c0->irqnum,NULL);
	device_destroy(c0->devcls,MKDEV(c0->dev_major,0));
	class_destroy(c0->devcls);
	unregister_chrdev(c0->dev_major,"chr_dev_test");
	kfree(c0);
	printk("exit ok\n");
}

module_init(chr_dev_init);
module_exit(chr_dev_exit);
MODULE_LICENSE("GPL");

